# -*- coding: utf-8 -*-
import shutil,time,sys
import paramiko

hostname='120.27.201.238'
username='fnadmin'
password='fn!@#fn123$%^&*'
port=15388

# 输出Txt文本
def outputTxt(testResult):
    f = open(u'output.txt', 'a', 0)
    f.truncate()
    f.write("用户编号\t掉线次数\t企业编号\t企业名称\t            用户Code\t            用户名称\n")
    for index1 in range(len(testResult)):
        f.write(str(testResult[index1]["userId"])+"\t"\
                +str(testResult[index1]["dropTimes"])+"\t"\
                +str(testResult[index1]["companyId"])+"\t"\
                +str(testResult[index1]["companyName"])+"\t"\
                +str(testResult[index1]["userCode"])+"\t"\
                +str(testResult[index1]["userName"])+"\t\n")
    f.close()

def lenAdjust(string,length):
    if len(string) < int(length):
        delLen = int(length) - len(string)
        string = str(string) + " "*delLen
        return string
    else:
        return string

class userStatistical():
    def __init__(self):
        self.userArray = []
        self.userIdArray = []

    def userAdd(self,userId,dropTimes,companyId="",companyName="",userCode="",userName=""):
        if len(self.userArray)==0:
            newUser = {"userId":str(userId), "dropTimes":str(dropTimes), "companyId":str(companyId), "companyName":companyName, "userCode":userCode, "userName":userName}
            self.userArray.append(newUser)
            self.userIdArray.append(userId)
        else:
            statusIn = False
            for user in self.userArray:
                if(user["userId"]==str(userId)):
                    statusIn = True
                    user["dropTimes"]=str(int(user["dropTimes"])+1)
            if statusIn == False:
                newUser = {"userId":str(userId), "dropTimes":str(dropTimes), "companyId":str(companyId), "companyName":companyName, "userCode":userCode, "userName":userName}
                self.userArray.append(newUser)
                self.userIdArray.append(userId)
                
    def userSum(self,userId,dropTimes,companyId="",companyName="",userCode="",userName=""):
        if len(self.userArray)==0:
            newUser = {"userId":str(userId), "dropTimes":str(dropTimes), "companyId":str(companyId), "companyName":companyName, "userCode":userCode, "userName":userName}
            self.userArray.append(newUser)
            self.userIdArray.append(userId)
        else:
            statusIn = False
            for user in self.userArray:
                if(user["userId"]==userId):
                    statusIn = True
                    user["dropTimes"]=str(int(user["dropTimes"])+int(dropTimes))
            if statusIn == False:
                newUser = {"userId":str(userId), "dropTimes":str(dropTimes), "companyId":str(companyId), "companyName":companyName, "userCode":userCode, "userName":userName}
                self.userArray.append(newUser)
                self.userIdArray.append(userId)

if __name__ == "__main__":
    reportResult = userStatistical()
    #step1: execute the python script in bastion host
    print "########## step1: execute the python script in serverhost ##########"
    ssh=paramiko.SSHClient()                                                    
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())                   
    ssh.connect(hostname=hostname,port=port,username=username,password=password)

    stdin,stdout,stderr=ssh.exec_command("python /home/fnadmin/workPathForFan/dropStatistical/dropStatistical.py")
    print stdout.read()

    
    #step2: read the result of executing the python script
    print "########## step2: read the result of executing the python script ##########"
    stdin,stdout,stderr=ssh.exec_command("cat /home/fnadmin/workPathForFan/dropStatistical/output.txt|sort -rn -k2")
    resultInfo = stdout.read()
    print resultInfo

    #step3: save the ack result
    print "########## step3: save the ack result ##########"
    resultInfoArray = resultInfo.split('\n')
    for userInfo in resultInfoArray:
        userInfoArray = userInfo.split("\t")
        if (userInfoArray[0]==""):
            continue
        reportResult.userAdd(userInfoArray[0],userInfoArray[1],userInfoArray[2],userInfoArray[3],userInfoArray[4],userInfoArray[5])

    ssh.close()
    #step4: adjust the length of the data fields and output the info
    print "########## step4: adjust the length of the data fields and output the info ###########"
    for user in reportResult.userArray:
        user["userId"] = lenAdjust(user["userId"],10)
        user["dropTimes"] = lenAdjust(str(user["dropTimes"]),10)
        user["companyId"] = lenAdjust(user["companyId"],10)
        user["companyName"] = lenAdjust(user["companyName"],25)
        user["userCode"] = lenAdjust(user["userCode"],20)
        user["userName"] = lenAdjust(user["userName"],20)

    outputTxt(reportResult.userArray)
    print("=================================END=====================================")
    time.sleep(5)
